import { ExecutionContext, Injectable, UnauthorizedException } from '@nestjs/common';
import { Observable } from 'rxjs';
import { DecoratorEnum } from '../enums/decorator.enum';
import { Reflector } from '@nestjs/core';
import { AuthGuard } from '@nestjs/passport';
import { StrategyEnum } from '../enums/strategy.enum';

@Injectable()
export class JwtAccessGuard extends AuthGuard(StrategyEnum.JWT_ACCESS) {
  constructor(private readonly reflector: Reflector) {
    super();
  }
  canActivate(
    context: ExecutionContext,
  ): boolean | Promise<boolean> | Observable<boolean> {
    const isPublic = this.reflector.getAllAndOverride(DecoratorEnum.IS_PUBLIC, [
      context.getHandler(),
      context.getClass()
    ])
    if (isPublic) return true;
    return super.canActivate(context);
  }


  handleRequest<TUser = any>(err: any, user: any, info: any, context: ExecutionContext, status?: any): TUser {
    if (err || !user) {
      throw err || new UnauthorizedException(info)
    }
    // 默认挂载在req上
    return user;
  }
}
